<template>
    <div class="container">
        <!-- 提示 -->
        <el-tag
            type="warning"
            :style="{marginBottom: '15px'}"
        >提示:答题选项的正确答案从0开始</el-tag>
        <!-- header -->
        <div class="header">
            <div class="header-left">
                <p class="header-name">选择学校:</p>
                <el-select
                    v-model="status"
                    filterable
                    placeholder="请选择"
                    size="small"
                    @change="getTableData(1)"
                >
                    <el-option
                        v-for="item in option"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
                <div class="btn-import-wrap">
                    <input
                        class="import-input"
                        accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                        type="file"
                        @change="tirggerFile($event)">
                    <el-button
                        size="mini"
                        type="primary">导入试题</el-button>
                </div>
                <el-button
                    size="mini"
                    class="btn-download"
                    @click="fnDownLoad"
                    type="primary">下载试题模版</el-button>
            </div>
            <div class="header-right">
                <el-button
                    type="primary"
                    size='small'
                    @click="fnCreateQu()"
                >新建
                </el-button>
            </div>
        </div>
        <!-- /header -->

        <!-- table -->
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            border
        >
            <el-table-column
                label="ID"
                width="100px"
                type="index"
                align="center"
            />
            <el-table-column
                prop="school_name"
                label="学校"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="question_title"
                label="题目"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            />
            <el-table-column
                prop="question_type"
                label="类型"
                show-overflow-tooltip
                :formatter="emptyFormatter"
            >
                <template slot-scope="scope">
                    <span
                        class="social-type"
                        v-if="scope.row.question_type == 'radio' "
                    >单选</span>
                    <span
                        v-else
                        class="social-type"
                    >其它</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="question_option_list"
                label="选项"
                show-overflow-tooltip
            >
                <template slot-scope="scope">
                    <p
                        v-for="(item,index) in scope.row.question_option_list"
                        :key="index"
                        class="option_list"
                    >{{ index }}: {{ item }}</p>
                </template>
            </el-table-column>
            <el-table-column
                prop="question_answer_index"
                label="正确答案"
            >
                <template slot-scope="scope">
                    {{ scope.row.question_answer_index }}
                </template>
            </el-table-column>
            <el-table-column
                prop="question_score"
                label="分值"
            />
            <!-- <el-table-column
                prop="question_sort"
                label="排序"
            >
                <template slot-scope="scope">
                    <div class="sort-wrap">
                        {{ scope.row.question_sort }}
                        <span class="sort-spliter" />
                        <el-button
                            type="text"
                            class="btn-sort"
                            @click="fnEditSort(scope.row)"
                        >
                            <i class="el-icon-edit" />
                        </el-button>
                    </div>
                </template>
            </el-table-column> -->
            <el-table-column
                prop="question_status"
                label="状态"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.question_status == 1">启用</span>
                    <span v-if="scope.row.question_status == 0">禁用</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                fixed="right"
                :width="250"
            >
                <template slot-scope="scope">
                    <span
                        class="curse-edit"
                        @click="fnEditQu(scope.row)"
                    >编辑</span>
                    <span
                        class="curse-disable"
                        @click="fnDisableQu(scope.row)"
                        v-if="scope.row.question_status == 1"
                    >禁用</span>
                    <span
                        class="curse-disable"
                        @click="fnDisableQu(scope.row)"
                        v-if="scope.row.question_status == 0"
                    >启用</span>
                    <span
                        class="curse-delete"
                        @click="fnDeleteQu(scope.row.question_no)"
                    >删除</span>
                </template>
            </el-table-column>
        </el-table>
        <!-- /table -->

        <!-- dialog -->
        <el-dialog
            title="新建试题"
            width="530px"
            custom-class="schedule-dialog"
            :visible.sync="showAddDialog"
        >
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
            >
                <el-form-item
                    prop='title'
                    label="题目"
                >
                    <el-input
                        placeholder="请输入题目标题"
                        v-model="ruleForm.title"
                        class="question-title"
                    />
                </el-form-item>
                <el-form-item
                    label="选项"
                    prop="resource"
                >
                    <el-radio-group
                        class="question-resource"
                        v-model="ruleForm.resource"
                    >
                        <div class="question">
                            <el-radio label="0"/>
                            <el-form-item
                                prop="answer"
                            >
                                <el-input
                                    placeholder="请填写完整内容"
                                    v-model="ruleForm.answer"
                                    class="question-answer"
                                />
                            </el-form-item>
                        </div>
                        <div class="question">
                            <el-radio label="1"/>
                            <el-form-item
                                prop="answerTwo"
                            >
                                <el-input
                                    placeholder="请填写完整内容"
                                    v-model="ruleForm.answerTwo"
                                    class="question-answer"
                                />
                            </el-form-item>
                        </div>
                        <div class="question">
                            <el-radio label="2"/>
                            <el-form-item
                                prop="answerThree"
                            >
                                <el-input
                                    placeholder="请填写完整内容"
                                    v-model="ruleForm.answerThree"
                                    class="question-answer"
                                />
                            </el-form-item>
                        </div>
                        <div class="question">
                            <el-radio label="3"/>
                            <el-form-item
                                prop="answerFour"
                            >
                                <el-input
                                    placeholder="请填写完整内容"
                                    v-model="ruleForm.answerFour"
                                    class="question-answer"
                                />
                            </el-form-item>
                        </div>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="small"
                    type="primary"
                    @click="submitForm('ruleForm')">提交</el-button>
            </div>
        </el-dialog>
        <!-- dialog -->

        <!-- 分页 -->
        <div
            class="pagination-wrapper clearfix"
            v-if="tableData.length > 0"
        >
            <el-pagination
                background
                layout="total, prev, pager, next"
                :current-page.sync="page.now_page"
                :total="page.total_count"
                :page-size="page.page_size"
                @current-change="getTableData"
            />
        </div>
        <!-- /分页 -->
    </div>
</template>

<script>
export default {
    data () {
        return {
            status: '',
            option: [{
                value: '',
                label: '全部'
            }],
            tableData: [],
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            showAddDialog: false,
            ruleForm: {
                title: '',
                resource: '',
                answer: '',
                answerTwo: '',
                answerThree: '',
                answerFour: ''
            },
            question_no: '',
            rules: {
                title: [
                    { required: true, message: '请填写题目名称', trigger: 'blur' }
                ],
                resource: [
                    { required: true, message: '请选择对应选项', trigger: 'blur' }
                ],
                answer: [
                    { required: true, message: '请填写选项内容', trigger: 'blur' }
                ],
                answerTwo: [
                    { required: true, message: '请填写选项内容', trigger: 'blur' }
                ],
                answerThree: [
                    { required: true, message: '请填写选项内容', trigger: 'blur' }
                ],
                answerFour: [
                    { required: true, message: '请填写选项内容', trigger: 'blur' }
                ]
            }
        };
    },
    computed : {
    },
    created () {
        this.setHeader();
        this.getTableData();
        this.getSchoolList();
    },
    methods: {
        /**
         * 下载试题
         */
        fnDownLoad () {
            let base = this.$baseUrl;
            let ticket = localStorage.getItem('sessionTicket');
            let url = `${base}/student/exam_question%5Ccsv?school_id=${this.status}&__ticket=${ticket}`;

            window.open(url);
        },

        /**
         * 设置表单header
         */
        setHeader () {
            this.$store.commit('SET_HEADER', [{
                title: "APP后台",
            },
            {
                title: '社交'
            },
            {
                title: "试题列表"
            }]
            );
        },

        /**
         * 获取已开通学校列表
         */
        getSchoolList () {
            this.$post('/student/forum%5Cget_school_list', {
            }, resp => {
                if (resp.code == 1) {
                    let list = [];

                    resp.data.list.map(item => {
                        list.push({
                            value: item.forum_no,
                            label: item.school_name
                        });
                    });

                    this.option = this.option.concat(list);
                }
            });
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/exam_question%5Cget_list', {
                page_id: page || this.page.now_page,
                forum_no: this.status
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;
                    this.page.now_page = resp.data.page.now_page;
                    this.page.total_count = resp.data.page.total_count;
                    this.page.page_size = resp.data.page.page_size;
                }
            });
        },

        /**
         * 导入试题
         */
        tirggerFile (event) {
            let file = event.target.files[0];
            let form = new FormData();

            form.append("file", file);
            this.$post('/student/exam_question%5Cimport', form, resp => {
                event.target.value = null;
                if (resp.code == 1) {
                    this.getTableData(1);
                    this.$message({
                        type: 'success',
                        message: '导入成功' || resp.msg,
                        center: true
                    });
                } else {
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * 新建试题
         */
        fnCreateQu () {
            if (this.status == '') {
                this.$message({
                    type: 'warning',
                    message: '请先选择学校'
                });
                return ;
            }
            this.ruleForm = {
                title: '',
                resource: '',
                answer: '',
                answerTwo: '',
                answerThree: '',
                answerFour: ''
            };
            this.question_no = '';
            this.showAddDialog = !this.showAddDialog;
        },

        /**
         * 提交试题  分数固定4分
         */
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let list = [];

                    list.push(
                        this.ruleForm['answer'],
                        this.ruleForm['answerTwo'],
                        this.ruleForm['answerThree'],
                        this.ruleForm['answerFour']
                    );
                    this.$post('/student/exam_question%5Csave', {
                        question_no: this.question_no,
                        forum_no: this.status,
                        question_title: this.ruleForm.title,
                        question_option_json: JSON.stringify(list),
                        question_answer_index: this.ruleForm.resource, //答案索引从0开始
                        question_score: '10',
                        question_sort: '20'
                    }, resp => {
                        if (resp.code == 1) {
                            this.$message({
                                type: 'success',
                                message: '提交成功!'
                            });
                            this.showAddDialog = !this.showAddDialog;
                            this.getTableData(1);
                        } else if (resp.code == 0) {
                            this.$message({
                                type: 'warning',
                                message: resp.msg
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 编辑试题
         */
        fnEditQu (row) {

            if (this.status == '') {
                const school_name = row.school_name;

                this.option.map(item => {
                    if(item.label == school_name) {
                        this.status = item.value;
                    }
                    return;
                });
            }

            this.showAddDialog = !this.showAddDialog;
            this.question_no = row.question_no;
            this.$post('/student/exam_question%5Cget', {
                question_no: row.question_no,
            }, resp => {
                if (resp.code == 1) {
                    const data = resp.data;
                    const option = data.question_option_list;

                    this.ruleForm = {
                        title: data.question_title,
                        answer: option[0],
                        answerTwo: option[1],
                        answerThree: option[2],
                        answerFour: option[3],
                        resource: data['question_answer_index'].toString()
                    };

                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 启用/禁用
         */
        fnDisableQu (row) {
            let question_no = row.question_no;
            let status = row.question_status;

            status = status == 1 ? status = 0 : status = 1;

            this.$post('/student/exam_question%5Cset_status', {
                question_no: question_no,
                question_status: status
            }, resp => {
                if (resp.code == 1) {
                    this.$message({
                        type: 'success',
                        message: '操作成功!'
                    });
                    this.$set(row, 'question_status', status);
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg
                    });
                }
            });
        },

        /**
         * 删除试题
         */
        fnDeleteQu (no) {
            this.$confirm('此操作将删除该试题, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/exam_question%5Cdelete', {
                    question_no: no
                }, resp => {
                    if (resp.code == 1) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getTableData(1);
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            }).catch(() => {
            });
        },

        /**
         * 排序
         */
        fnEditSort (row) {
            this.$prompt('请输入排序号', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^([1-9]\d?|[1-9]\d+)$/,
                inputErrorMessage: '排序号格式不正确,请重新输入'
            }).then(({ value }) => {
                this.$post('/student/exam_question%5Cset_sort',{
                    question_no: row.question_no,
                    question_sort: value
                },resp=>{
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '操作成功'
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg
                        });
                    }
                });
            });
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) {
                return '--';
            }
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
    .container {
        background-color: #fff;
        padding: 15px;
        display: flex;
        flex-direction: column;
        position: relative;
        .header {
            margin-bottom: 20px;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .header-left {
                display: flex;
                align-items: center;
                .header-name {
                    color: #606266;
                    margin-right: 8px;
                }
            }
            .header-right {
                display: flex;
                .el-button {
                    margin-left: 20px;
                }
            }
            .btn-import-wrap {
                margin-left: 15px;
                display: inline-block;
                position: relative;
                overflow: hidden;
                cursor: pointer;
                vertical-align: top;
                .import-input {
                    margin-left: -100%;
                    position: absolute;
                    left: 0;
                    top: 0;
                    width: 200%;
                    height: 100%;
                    cursor: pointer;
                    opacity: 0;
                }
            }
            .btn-download {
                margin-left: 20px;
            }
        }
        .pagination-wrapper {
            padding-top: 10px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
        .question-resource {
            display: block;
            margin-top: 45px;
        }
        .question-title {
            width: 93%;
            display: block;
        }
        .question{
            padding-left: 10px;
            display: flex;
            align-items: center;
            margin-top: 30px;
            .question-answer {
                width: 300px;
            }
        }
        .option_list {
            line-height: 28px;
        }
        .dialog-footer {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .el-form-item .el-form-item {
            margin-left: 20px;
        }
        .curse-edit , .curse-disable, .curse-delete{
            color: rgb(64, 158, 255);
            margin-right: 5px;
            cursor: pointer;
        }
    }
</style>
<style lang="less">
    .el-table__body-wrapper .el-table__body .el-table__row td {
        border-right: none;
    }
    .el-table__header-wrapper .el-table__header .has-gutter tr th {
        border-right: none;
    }
</style>
